/**
 * Created by Freeman on 2016/6/27.
 */
"use strict";

var _ = require('lodash'),
    MarkdownIt = require('markdown-it'),
    mongoose = require('../../models/mongoosedb').mongoose,
    Article = require('../../models/article.model'),
    User = require('../../models/user.model'),
    esearch = require('../../esearch/elasticsearch');

//添加博客
exports.saveArticle = function (req,res,next) {
    var id = req.body.id;
    var content = req.body.content;
    var title = req.body.title;
    var userId = req.user._id;
    var error_msg;
    if(!title){
        error_msg = '标题不能为空.';
    }else if(!content){
        error_msg = '内容不能为空.';
    }
    if(error_msg){
        return res.status(422).send({error_msg:error_msg});
    }
    if(id){
        Article.findByIdAndUpdate(id,{
            title:title,
            content:content,
            author_id:userId,
            updated:new Date()
        }).then(function (result) {
            return res.status(200).json({success: true,article_id:result._id});
        }).catch(function (err) {
            return next(err);
        });
    }else {
        //将图片提取存入images,缩略图调用
        Article.createAsync({
            title:title,
            content:content,
            author_id:userId
        }).then(function (result) {
            Article.findById(result._id)
                .populate({
                    path: 'author_id',
                    select: 'nickname avatar'
                }).exec().then(function (doc) {
                esearch.addDocument(doc).then(function (data) {
                    console.log(data)
                });
            });

            return res.status(200).json({success: true,article_id:result._id});
        }).catch(function (err) {
            return next(err);
        });
    }
};

//前台分页获取博客
exports.getFrontArticleList = function (req,res,next) {
    var pageNo = (parseInt(req.query.pageNo)>0)?parseInt(req.query.pageNo):1;
    var pageSize = (parseInt(req.query.pageSize)>0)?parseInt(req.query.pageSize):10;
    var startRow = (pageNo-1)*pageSize;
    var sort = String(req.query.sortName) || "publish_time";
    sort = "-" + sort;
    var condition = {status:{$gt:0}};

    if (req.query.tagId){
        var tagId = String(req.query.tagId);
        condition = _.defaults(condition,{tags:{ $elemMatch: { $eq:tagId } }})
    }
    if (req.query.userId){
        var userId = String(req.query.userId);
        condition = _.defaults(condition,{author_id:userId})
    }

    Article.find(condition)
        .populate({
            path: 'author_id',
            select: 'nickname avatar'
        })
        .select('title content images visit_count comment_count like_count publish_time author_id')
        .sort(sort)
        .skip(startRow)
        .limit(pageSize)
        .exec().then(function (list) {
            return res.status(200).json({data:list});
        }).then(null,function (err) {
            return next(err);
        });
}
//前台获取博客数量
exports.getFrontArticleCount = function (req,res,next) {
    var condition = {status:{$gt:0}};
    Article.countAsync(condition).then(function (count) {
        return res.status(200).json({success:true,count:count});
    }).catch(function (err) {
        return next(err);
    })
}

exports.getArticleById = function (req,res,next) {
    var id = req.params.id;
    var md = new MarkdownIt({
        html:true //启用html标记转换
    });
    //每次获取之后,将阅读数加1
    return Article.findByIdAsync(id,'-images').then(function(result) {
        //将content markdown文档转成HTML
        result.content = md.render(result.content);
        result.visit_count++;
        Article.findByIdAndUpdateAsync(id,{$inc:{visit_count:1}});
        return res.status(200).json({data:result.info});
    }).catch(function (err) {
        return next(err);
    });
}

exports.toggleLike = function (req,res,next) {
    var id = req.params.id;
    var aid = new mongoose.Types.ObjectId(id);
    var userId = req.user._id;
    var isLike = _.findIndex(req.user.likeList, function(item) {
        return item.toString() == req.params.id;
    });
    var conditionOne,conditionTwo,liked;
    if(isLike !== -1){
        conditionOne = {'$pull':{'likeList':aid}};
        conditionTwo = {'$inc':{'like_count':-1}};
        liked = false;
    }else{
        conditionOne = {'$addToSet':{'likeList':aid}};
        conditionTwo = {'$inc':{'like_count':1}};
        liked = true;
    }
    User.findByIdAndUpdateAsync(userId,conditionOne).then(function (user) {
        return Article.findByIdAndUpdateAsync(aid,conditionTwo,{new:true}).then(function (article) {
            return res.status(200).json({success:true,'count':article.like_count,'isLike':liked});
        });
    }).catch(function (err) {
        return next(err);
    });
}

exports.deleteArticle = function (req,res,next) {
    var id = req.params.id;

    return Article.findByIdAndRemoveAsync(id).then(function(result) {

        return res.status(200).json({data:result.info});
    }).catch(function (err) {
        return next(err);
    });
}

exports.updateArticle = function (req,res,next) {
    var id = req.params.id;

    return Article.findByIdAndUpdate(id,req.body).then(function(result) {

        return res.status(200).json({data:result.info});
    }).catch(function (err) {
        return next(err);
    });

}